搜索 K
Appearance
博客正在加载中...
Appearance
讲讲更多关于配置文件的知识
SpringBoot 文档中,有专门一节讲配置文件的:
4.2. Externalized Configuration
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments.
You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration.
Property values can be injected directly into your beans by using the
@Valueannotation, accessed through Spring's Environment abstraction, or be bound to structured objects through@ConfigurationProperties. 大意:
@Value 注解直接注入 bean 中,也可以使用 @ConfigurationProperties 将一系列配置绑定到对象中例如,我们之前安装 Java 和 Maven 的时候,都设置过环境变量。我们可以在代码中取出 Maven 的环境变量:
@RestController
public class HelloController {
@Value("${MAVEN_HOME}")
private String mvn;
@GetMapping("/mvn")
public String getMvn() {
return mvn;
}
} 效果:

还可以遍历所有的环境变量,以及一些系统信息(例如 Windows 版本等):
@SpringBootApplication
public class LearnSpringBootProfileApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(LearnSpringBootProfileApplication.class, args);
ConfigurableEnvironment environment = run.getEnvironment();
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
Map<String, Object> systemProperties = environment.getSystemProperties();
System.out.println(systemEnvironment);
System.out.println(systemProperties);
}
}运行结果:

Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order:
- Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.
- @TestPropertySource annotations on your tests.
- properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
- Command line arguments.
- .....
大意:SpringBoot 对于加载配置有指定的顺序,并且允许覆盖,越下方的优先级越高(文档中列了 17 个,这里不全部举出),也不用全部记住,只需记得后面的配置会覆盖前面的配置即可
关于配置文件 application.yaml,也是有加载顺序的:
也就是从上往下,逐个加载这些配置文件(如果没有则不加载) 例如,在 resources 目录下新建 config 目录,然后新建 application.yaml:
spring:
profiles:
active: test 运行结果:test 配置文件被加载

我们总结下加载文件的顺序:
首先加载 application.yaml 文件,根据如下路径加载
然后加载指定的 Profile 由于后面加载的配置,会覆盖前面加载的配置,因此可以认为后面的配置优先级较高。